package org.devocean.groupbuying.service.security;

import java.util.ArrayList;
import java.util.Collection;

import org.devocean.groupbuying.dao.CustomerDAO;
import org.devocean.groupbuying.domain.Customer;
import org.devocean.groupbuying.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CustomerDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private CustomerDAO customerDAO;

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username)

	throws UsernameNotFoundException, DataAccessException {
		Customer customerEntity = customerDAO.findCustomer(username);
		if (customerEntity == null)
			throw new UsernameNotFoundException("user not found");

		return buildUserFromUserEntity(customerEntity);
	}

	public User buildUserFromUserEntity(Customer customerEntity) {

		String principalName = String.valueOf(customerEntity.getCustomerID());
		String password = customerEntity.getPassword();
		boolean enabled = customerEntity.getEnabled();
		boolean accountNonExpired = customerEntity.getEnabled();
		boolean credentialsNonExpired = customerEntity.getEnabled();
		boolean accountNonLocked = customerEntity.getEnabled();

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (Role role : customerEntity.getCustomerRoles()) {
			authorities.add(new GrantedAuthorityImpl(role.getAuthority()));
		}

		User user = new User(principalName, password, enabled,
				accountNonExpired, credentialsNonExpired, accountNonLocked,
				authorities);
		return user;
	}
}
